package cn.atzxc.qy.utils;

import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * JWT工具类
 */
public class JwtUtil {

    //有效期为
    public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000  一个小时
    //设置秘钥明文
    public static final String JWT_KEY = "sangeng";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }
    
    /**
     * 重载一：
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        return builder.compact();
    }
    /**
     * 重载二：
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }
    /**
     * 重载三：
     * 创建token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

    /*
    * JWT配置信息
    * */
    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("sg")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);
    }



    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    
    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    //根据token解析出指定的用户ID
    public static String getUserIdFromToken(String token) throws Exception {
        //通过token解析出指定的用户名ID
        Claims claims = JwtUtil.parseJWT(token);
        String subject = claims.getSubject();
        return subject;
    }

    public static void main(String[] args) throws Exception {
        /*
        * 加密数据
        * 三种重载形式
        *
        * eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0NDIzYWFiZWE5MjE0ZmNkYTQxOTljOGE0YzE4MjlkMCIsInN1YiI6IjEyMzEyMyIsImlzcyI6InNnIiwiaWF0IjoxNzA2NTA0NDkwLCJleHAiOjE3MDY1MDgwOTB9.0WWa1v8kSufOvI5pk6oBFkWEQ9tH5j3XDComlGM6gjA
        * */
        String jwt = createJWT("{\n" +
                "    \"username\":\"admin\",\n" +
                "    \"password\":\"1234\"\n" +
                "}");
        System.out.println(jwt);

        String jwt1 = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJlY2YzYTZlYjgwYjE0N2I1YTk5ZDU2ZDMyNzUxNWQ4NiIsInN1YiI6IlRlc3RVc2VyKGlkPTgsIHVzZXJuYW1lPWFkbWluLCBwYXNzd29yZD0kMmEkMTAkdHRpdEN0WEEzUUZnSkJkTUtWUXRVdVlCREhpdDJPQTZQWTlZVUo1WHM1ZDlYa1c1NkNhRWksIGVtYWlsPW51bGwpIiwiaXNzIjoic2ciLCJpYXQiOjE3MDY1MDUzNjcsImV4cCI6MTcwNjUwODk2N30.sOnZHitdqLK6Jt26LMTE8FBM3nH_gVtN6mIXY5Vzp4A";
        System.out.println(jwt1);
        /*
        * 解密
        * */
        Claims claims = parseJWT(jwt1);
        String subject = claims.getSubject();
        System.out.println(subject);

    }


}